package cn.lyq.card.ui.realname

import android.content.Intent
import android.net.Uri
import androidx.lifecycle.Observer
import cn.lyq.card.R
import cn.lyq.card.base.BaseActivity
import cn.lyq.card.data.src.Status
import cn.lyq.card.manager.PhoneCodeManager
import cn.lyq.card.manager.UserManager
import cn.lyq.card.ui.result.ResultActivity
import cn.lyq.card.utils.loadUrl
import cn.lyq.card.utils.setClick
import com.blankj.utilcode.util.*
import kotlinx.android.synthetic.main.act_real_name_auth.*
import java.io.File

class RealNameAuthActivity : BaseActivity() {

    companion object {
        private const val KEY_IMAGE_ID = 1000
    }

    private val mModel by lazy {
        getVM(RealNameAuthVM::class.java)
    }
    private var imgIdUrl: String? = null
    private var imgIdReverseUrl: String? = null
    private var isReverse = false
    private lateinit var targetUri: Uri

    override fun getLayoutId(): Int {
        return R.layout.act_real_name_auth
    }

    override fun initView() {
        super.initView()
        setMyTitle(R.string.str_real_name_auth)
    }

    override fun initListener() {
        super.initListener()
        tvConfirm.setClick {
            if (imgIdUrl?.isEmpty() != false) {
                ToastUtils.showShort(tvImgId.text)
                return@setClick
            }
            if (imgIdReverseUrl?.isEmpty() != false) {
                ToastUtils.showShort(tvImgIdReverse.text)
                return@setClick
            }
            val name = etName.text.toString().trim()
            if (name.isEmpty()) {
                ToastUtils.showShort(etName.hint)
                return@setClick
            }
            val idCode = etId.text.toString().trim()
            if (idCode.isEmpty()) {
                ToastUtils.showShort(etId.hint)
                return@setClick
            }
            val bankCard = etCard.text.toString().trim()
            if (bankCard.isEmpty()) {
                ToastUtils.showShort(etCard.hint)
                return@setClick
            }
            val code = etCode.text.toString().trim()
            if (code.isEmpty()) {
                ToastUtils.showShort(etCode.hint)
                return@setClick
            }
            verify(name, idCode, bankCard, code)
        }
        imgId.setClick {
            gotoCapture(false)
        }
        tvImgId.setClick {
            gotoCapture(false)
        }
        imgIdReverse.setClick {
            gotoCapture(true)
        }
        tvImgIdReverse.setClick {
            gotoCapture(true)
        }

        tvGetCode.setClick {
            PhoneCodeManager.sendMsgCode(6)
        }
    }

    private fun gotoCapture(isReverse: Boolean) {
        this.isReverse = isReverse
        val file = File(
            "${PathUtils.getExternalAppPicturesPath()}/id",
            "${System.currentTimeMillis()}.jpg"
        )
        FileUtils.createOrExistsFile(file)
        targetUri = UriUtils.file2Uri(file)
        startActivityForResult(IntentUtils.getCaptureIntent(targetUri), KEY_IMAGE_ID)
    }

    private fun verify(name: String, idCode: String, bankCard: String, code: String) {
        mModel.verifyRealName(name, idCode, bankCard, code, imgIdUrl ?: "", imgIdReverseUrl ?: "")
            .observe(this, Observer {
                when (it?.status) {
                    Status.LOADING -> showLoading()
                    Status.SUCCESS -> {
                        dismissLoading()
                        UserManager.instance.value?.idCardStatus = 0
                        ResultActivity.start(this, 1)
                        finish()
                    }
                    Status.ERROR -> {
                        dismissLoading()
                        ToastUtils.showShort(it.message.getMsg())
                    }
                }
            })
    }

    override fun initObserver() {
        super.initObserver()
        PhoneCodeManager.countDown.observe(this, PhoneCodeManager.observer(tvGetCode))
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == KEY_IMAGE_ID) {
            if (resultCode == RESULT_OK) {
                if (isReverse) {
                    imgIdReverse.loadUrl(targetUri)
                } else {
                    imgId.loadUrl(targetUri)
                }
                upload(UriUtils.uri2File(targetUri))
            }
        }
    }

    private fun upload(file: File) {
        val isReverseTemp = isReverse
        mModel.upload(file).observe(this, Observer {
            when (it?.status) {
                Status.LOADING -> showLoading()
                Status.SUCCESS -> {
                    if (isReverseTemp) {
                        imgIdReverseUrl = it.requireData().path
                    } else {
                        imgIdUrl = it.requireData().path
                    }
                    dismissLoading()
                    ToastUtils.showShort(R.string.str_upload_success)
                }
                Status.ERROR -> {
                    dismissLoading()
                    ToastUtils.showShort(it.message.getMsg())
                }
            }
        })
    }

    override fun onDestroy() {
        super.onDestroy()
        PhoneCodeManager.reset()
    }
}